var base64 = new Base64();
var technician = new Vue({
    el: '#app',
    data() {
        return {
            info: {
                name: '',
                phoneNum: '',
                cardSn: '',
                merchantCode: '',
                token: '',
                headimgurl: '',
                auroraId: ''
            },
            curData: {
                cosmetologyMoney: 0,
                year: 0,
                receiptQuantity: 0,
                cosmetologyQuantity: 0,
                complaintQuantity: 0,
                carWashQuantity: 0,
                negativeCommentQuantity: 0,
                reviewQuantity: 0,
                receiptTime: 0,
                month: 0,
                due: 0,
                carWashMoney: 0,
                praiseQuantity: 0
            },
            code: '',
            allturnover: 0.0,
            todayturnover: 0.0,
            todayquantity: 0,
            orderStatus: {
                PENDING: 0,
                CHECK_PENDING: 1,
                UNACCEPTED: 2,
                ACCEPTED: 3,
                TRADE_SUCCESS: 4,
                TRADE_CLOSE: 5,
                WAIT_FOR_SERVICE: 6
            },
            unacceptedOrderQuantity: 0,
            vsersion: '',
            star: '../image/1star.png',
            starName: '喜哥',
            rRegistrationId: '',
            rankingList: [],
            countdownList: [],
            buttonCodeShow: true,
            counttime:60
        }
    },
    methods: {
        init: function() {
            technician.vsersion = api.appVersion;
            // 测试用代码，测试的时候请将注释取消
            // api.setGlobalData({
            //     key: 'useropenid',
            //     value: 'oKwXw0yCc9r8gASPvTalwiEgAJek'
            //     // value: 'oX4JM1KYTSs-V0atrXsdRmnFwyGI'
            // });
            // 测试用代码，测试的时候请将注释取消
            var openid = api.getGlobalData({
                key: 'useropenid'
            });
            console.log('=openid=' + openid + (openid != ''));
            if (openid != '') {
                this.login(openid, function(ret, err) {
                    api.setGlobalData({
                        key: 'technicianid',
                        value: ret.technician.id
                    });
                    technician.findAccount(ret.technician.id);
                    // technician.hasAcceptedOrderList(function(ret, err) {});
                    // technician.hasUnacceptedOrderList();
                    var date = new Date;
                    technician.curYear = date.getFullYear();
                    technician.curMonth = date.getMonth() + 1;
                    api.setGlobalData({
                        key: 'curYear',
                        value: technician.curYear
                    });
                    api.setGlobalData({
                        key: 'curMonth',
                        value: technician.curMonth
                    });
                    //技师排行榜
                    var paramsph = new Object();
                    var monthph = date.getMonth();
                    if (monthph == 0) {
                      paramsph.year = date.getFullYear()-1;
                      paramsph.month = 11;
                    } else {
                      paramsph.year = date.getFullYear();
                      paramsph.month = date.getMonth();
                    }
                    paramsph.order = 'desc'; // desc
                    paramsph.sort = 'due';
                    paramsph.per_page = 3;
                    technician.getRankingExpand(paramsph); //技师排行榜
                    paramsph.order = '';
                    paramsph.order = 'asc';
                    technician.getcountdownExpand(paramsph); //技师倒数排行榜

                    var params = new Object();
                    params.technician = api.getGlobalData({
                        key: 'technicianid'
                    });
                    params.year = technician.curYear;
                    params.month = technician.curMonth >= 10 ? technician.curMonth : '0' + technician.curMonth;
                    params.day = '';
                    params.groupBy = 'month'
                    technician.getImmediateOrders(params);
                    params.month = (technician.curMonth - 1) >= 10 ? (technician.curMonth - 1) : '0' + (technician.curMonth - 1);
                    technician.getTechnicianExpand(params);
                    //隐藏加载页面
                    api.hideProgress();
                });
            } else {
                this.initWXBind();
            }
        },
        // 验证码倒计时60秒
        countDowntime: function () {
            //var TIME_COUNT = 60;
            if (technician.counttime == 0) {
              technician.buttonCodeShow = true;
              technician.counttime = 60;
              return false;
            } else {
              technician.buttonCodeShow = false;
              technician.counttime--;
            }
            setTimeout(function() {
              technician.countDowntime();
            },1000);  
          },
        //技师排行榜
        getRankingExpand: function(params) {
            var url = 'v1/technicianExpand/?' +
                'year=' + params.year +
                '&month=' + params.month +
                '&sort=' + params.sort +
                '&order=' +  params.order +
                '&per_page=3&page=1'
                // console.log('tjUrl123:' + url);
                $api.ajax(function(ret, err) {
                    if (ret && ret.rows.length > 0) {
                       technician.rankingList = ret.rows;
                    /*  if (params.order == 'desc') {
                        technician.rankingList = ret.rows;
                        console.log('rankingList: '+JSON.stringify(technician.rankingList));
                      };
                      if (params.order == 'asc') {
                        technician.countdownList = ret.rows;
                        console.log('countdownList: '+JSON.stringify(technician.countdownList));
                      }; */
                    }
                }, url, 'get', {});
        },
        //技师倒数排行榜
        getcountdownExpand: function(params) {
            //console.log('params: ' + JSON.stringify(params));
            var url = 'v1/technicianExpand/?' +
                'year=' + params.year +
                '&month=' + params.month +
                '&sort=' + params.sort +
                '&order=' +  params.order +
                '&per_page=3&page=1'
                $api.ajax(function(ret, err) {
                    if (ret && ret.rows.length > 0) {
                       technician.countdownList = ret.rows;
                      // console.log('countdownList: '+JSON.stringify(technician.countdownList));
                    }
                }, url, 'get', {});
        },
        getTechnicianExpand: function(params) {
            var url = 'v1/technicianExpand/?page=1&order=&sortby=&per_page=1' +
                '&technician=' + params.technician +
                '&year=' + params.year +
                '&month=' + params.month
            $api.ajax(function(ret, err) {
                if (ret && ret.rows.length > 0) {
                    technician.star = '../image/' + ret.rows[0].star + 'star.png';
                    switch (ret.rows[0].star) {
                        case '2':
                            technician.starName = '二星喜哥';
                            break;
                        case '3':
                            technician.starName = '三星喜哥';
                            break;
                        case '4':
                            technician.starName = '四星喜哥';
                            break;
                        case '5':
                            technician.starName = '五星喜哥';
                            break;
                        default:
                            technician.starName = '喜哥';
                    }
                }
            }, url, 'get', {});
        },
        getImmediateOrders: function(params) {
            $api.ajax(function(ret, err) {
                console.log('ret: ' + JSON.stringify(ret));
                if (ret) {
                    technician.curData = ret;
                } else {
                    technician.curData = {
                        cosmetologyMoney: 0,
                        year: technician.curYear,
                        receiptQuantity: 0,
                        cosmetologyQuantity: 0,
                        complaintQuantity: 0,
                        carWashQuantity: 0,
                        negativeCommentQuantity: 0,
                        reviewQuantity: 0,
                        receiptTime: 0,
                        month: technician.curMonth,
                        due: 0,
                        carWashMoney: 0,
                        praiseQuantity: 0
                    }
                }
            }, 'v1/technicianExpand/getImmediateTechnicianData', 'post', params);
        },
        hasUnacceptedOrderList: function() {
            var params = {}
            params.technician = api.getGlobalData({
                key: 'technicianid'
            });
            params.status = this.orderStatus.UNACCEPTED;
            params.asc = true;
            $api.ajax(function(ret, err) {
                technician.unacceptedOrderQuantity = ret.length
            }, 'order/findOrderList', 'post', params);
        },
        hasAcceptedOrderList: function(callback) {
            var params = {}
            params.technician = api.getGlobalData({
                key: 'technicianid'
            });
            params.status = this.orderStatus.ACCEPTED + ',' + this.orderStatus.WAIT_FOR_SERVICE;
            params.asc = true;
            $api.ajax(function(ret, err) {
                if (ret.length > 0) {
                    api.setGlobalData({
                        key: 'curOrder',
                        value: ret[0]
                    });
                    alert('您还有进行中的订单，请先处理进行中的订单。');
                    if (ret[0].status == technician.orderStatus.ACCEPTED) {
                        technician.openwinHere('startorder');
                    } else if (ret[0].status == technician.orderStatus.WAIT_FOR_SERVICE) {
                        technician.openwinHere('makeorder');
                    }
                } else {
                    callback(ret, err);
                }
            }, 'order/findOrderList', 'post', params);
        },
        hasLogin: function(callback) {
            var technicianid = api.getGlobalData({
                key: 'technicianid'
            });
            if (technicianid != '') {
                callback();
            } else {
                var openid = api.getGlobalData({
                    key: 'useropenid'
                });
                this.login(openid, callback);
            }
        },
        hasToken: function(token) {
            $api.ajax(function(ret, err) {
                if (ret.openid == '') {
                    $api.ajax(function(ret, err) {
                        technician.login(ret.openid, function(ret, err) {
                            api.setGlobalData({
                                key: 'technicianid',
                                value: ret.technician.id
                            });
                            technician.findAccount(ret.technician.id);
                            var date = new Date;
                            technician.curYear = date.getFullYear();
                            technician.curMonth = date.getMonth() + 1;
                            api.setGlobalData({
                                key: 'curYear',
                                value: technician.curYear
                            });
                            api.setGlobalData({
                                key: 'curMonth',
                                value: technician.curMonth
                            });

                            var params = new Object();
                            params.technician = api.getGlobalData({
                                key: 'technicianid'
                            });
                            params.year = technician.curYear;
                            params.month = technician.curMonth >= 10 ? technician.curMonth : '0' + technician.curMonth;
                            params.day = '';
                            params.groupBy = 'month'
                            technician.getImmediateOrders(params);
                            technician.getTechnicianExpand(params);
                        });
                    }, 'technicianToken/', 'post', token);
                } else {
                    technician.login(ret.openid, function(ret, err) {
                        api.setGlobalData({
                            key: 'technicianid',
                            value: ret.technician.id
                        });
                        technician.findAccount(ret.technician.id);
                        var date = new Date;
                        technician.curYear = date.getFullYear();
                        technician.curMonth = date.getMonth() + 1;
                        api.setGlobalData({
                            key: 'curYear',
                            value: technician.curYear
                        });
                        api.setGlobalData({
                            key: 'curMonth',
                            value: technician.curMonth
                        });

                        var params = new Object();
                        params.technician = api.getGlobalData({
                            key: 'technicianid'
                        });
                        params.year = technician.curYear;
                        params.month = technician.curMonth >= 10 ? technician.curMonth : '0' + technician.curMonth;
                        params.day = '';
                        params.groupBy = 'month'
                        technician.getImmediateOrders(params);
                        technician.getTechnicianExpand(params);
                    });
                }
            }, 'technicianToken/has', 'post', token.openid);
        },
        login: function(openid, callback) {
            $api.ajax(function(ret, err) {
                if (ret) {
                    api.setGlobalData({
                        key: 'openid',
                        value: ret.openid
                    });
                    api.setGlobalData({
                        key: 'userheadimgurl',
                        value: ret.technician.headimgurl
                    });
                    api.setGlobalData({
                        key: 'technicianInfo',
                        value: ret.technician
                    });
                    if (ret.technician == '') {
                         //隐藏加载页面
                        api.hideProgress();
                        alert('还未注册，请先注册。');
                        $api.openWin('register');
                    } else {
                        technician.info = ret.technician
                        console.log('=login=' + JSON.stringify(technician.info));
                        callback(ret, err);
                    }
                } else {}
            }, 'technician/login', 'post', openid);
        },
        findAccount: function(id) {
            $api.ajax(function(ret, err) {
                technician.allturnover = ret.general.turnover;
                technician.todayturnover = ret.sevenDaysOfRevenue[6].turnover;
                technician.todayquantity = ret.sevenDaysOfRevenue[6].quantity;
                api.setGlobalData({
                    key: 'allturnover',
                    value: ret.general.turnover
                });
                api.setGlobalData({
                    key: 'todayturnover',
                    value: technician.todayturnover
                });
                api.setGlobalData({
                    key: 'todayquantity',
                    value: technician.todayquantity
                });
            }, 'technician/findAccount', 'post', id);
        },
        getCode: function() {
            $api.ajax(function(ret, err) {
                if (ret) {
                    api.toast({
                        msg: '验证码已发送，请查收。',
                        location: 'middle',
                        duration: 1900
                    });
                    technician.countDowntime();
                }
            }, 'sms/send', 'post', technician.info.phoneNum, 'text');
        },
        register: function() {
            if (technician.info.name == '') {
                api.toast({
                    msg: '请输入姓名',
                    location: 'middle',
                    duration: 1700
                });
                return;
            };
            if (technician.info.phoneNum == '') {
                api.toast({
                    msg: '请输入手机号码',
                    location: 'middle',
                    duration: 1700
                });
                return;
            };
            if (technician.info.cardSn == '') {
                api.toast({
                    msg: '请输入身份证号',
                    location: 'middle',
                    duration: 1700
                });
                return;
            };
            var reg = /(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            if (reg.test(technician.info.cardSn) == false) {
                api.toast({
                    msg: '身份证输入不合法',
                    location: 'middle',
                    duration: 1700
                });
                return;
            };
            if (technician.info.merchantCode == '') {
                api.toast({
                    msg: '请输入商户编码',
                    location: 'middle',
                    duration: 1700
                });
                return;
            };
            if (technician.code == '') {
                api.toast({
                    msg: '请输入验证码',
                    location: 'middle',
                    duration: 1700
                });
                return;
            };
            technician.info.token = api.getGlobalData({
                key: 'useropenid'
            });
            technician.info.headimgurl = api.getGlobalData({
                key: 'userheadimgurl'
            });
            //极光推送registrationid
            technician.info.auroraId = api.getGlobalData({
                key: 'rRegistrationId'
            });
            $api.ajax(function(ret, err) {
                if (ret) {
                    api.sendEvent({
                        name: 'orderover',
                        extra: {
                            msg: '订单完成'
                        }
                    });
                    api.closeToWin({
                        name: 'root'
                    });
                }
            }, 'technician/register', 'post', technician.info);
        },
        openwinHere: function(name) {
            var delay = 0;
            if (api.systemType != 'ios') {
                delay = 300;
            }
            api.openWin({
                name: '' + name + '',
                url: 'html/' + name + '.html',
                bounces: false,
                delay: delay,
                slidBackEnabled: true,
                vScrollBarEnabled: false
            });
        },
        goToSupplementphoto: function() {
            this.hasLogin(function(ret, err) {
                api.setFrameGroupIndex({
                    name: 'IndexGroup',
                    index: 5,
                    reload: true
                });
            });
        },
        // 微信授权登陆
        initWXBind: function() {
            wx = api.require('wx');
            wx.isInstalled(function(ret, err) {
                if (ret.installed) {
                    wx.auth({
                        apiKey: ''
                    }, function(ret, err) {
                        if (ret.status) {
                            wx.getToken({
                                apiKey: '',
                                apiSecret: '',
                                code: ret.code
                            }, function(ret, err) {
                                if (ret.status) {
                                    api.showProgress({
                                        style: 'default',
                                        animationType: 'fade',
                                        title: '授权成功',
                                        text: '绑定处理中...',
                                        modal: true
                                    });
                                    wx.getUserInfo({
                                        accessToken: ret.accessToken,
                                        openId: ret.openId
                                    }, function(ret, err) {
                                        if (ret.status) {
                                            api.setGlobalData({
                                                key: 'useropenid',
                                                value: ret.openid
                                            });
                                            api.setGlobalData({
                                                key: 'userheadimgurl',
                                                value: ret.headimgurl
                                            });
                                            api.setGlobalData({
                                                key: 'usernickname',
                                                value: ret.nickname
                                            });
                                            api.setGlobalData({
                                                key: 'userunionid',
                                                value: ret.unionid
                                            });
                                            technician.hasToken(ret);
                                            api.hideProgress();
                                        } else {
                                        }
                                    });
                                } else {
                                }
                            });
                        } else {
                        }
                    });
                } else {
                    alert('当前设备未安装微信客户端');
                }
            });
        }
    }
});
